# target
TARGET=nano

BUILD_DIR=build

# gcc
CROSS_COMPILE=arm-none-eabi-
CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
LD=$(CROSS_COMPILE)ld
DP=$(CROSS_COMPILE)objdump

# SRC 
SRC_C=src/printf.c src/main.c src/interrupt.c src/led.c src/gcc_startup.c src/syscalls.c  src/sysmem.c src/resets.c src/gpio.c src/sysclk.c src/uart.c src/cores.c

SRC_C+=$(wildcard TraceRecorder/*.c)
SRC_C+=$(wildcard TraceRecorder/streamports/RingBuffer/*.c)

SRC_C+=$(wildcard FreeRTOS-Kernel/*.c)
# SRC_C+=$(wildcard FreeRTOS-Kernel/portable/*.c)
SRC_C+=$(wildcard FreeRTOS-Kernel/portable/ARM_CM0/*.c)
SRC_S=src/bs2_default_padded_checksummed.S

SRC_LD=link.ld

OBJC=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJS=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_S:.S=.o)))

INC=-Isrc -I. -Iinc -IFreeRTOS-Kernel/include -IFreeRTOS-Kernel/portable/ARM_CM0 \
-ITraceRecorder/include \
-ITraceRecorder/config \
-ITraceRecorder/streamports/RingBuffer/include \
-ITraceRecorder/streamports/RingBuffer/config \
-Icmsis  #-IFreeRTOS-Kernel/portable/include

#CFLAGS
CFLAGS= \
-mcpu=cortex-m0plus \
-mthumb \
-mfloat-abi=soft \
-Wall \
-fdata-sections -ffunction-sections \
-g -g3 -O0

CFLAGS+= \
# --specs=nano.specs   

LIBS=\
#-lc -lm
#如果程序并不实际使用系统函数，但是某些代码引用了系统函数，那么可以引入libnosys，以便通过编译。
#LIBS+=-lnosys

# LD FLAGS
LDFLAGS=-mcpu=cortex-m0plus -mthumb \
-Wl,--gc-sections

LDFLAGS+=-T$(SRC_LD) $(LIBS)

LDFLAGS += -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref
 

#SET PATH %.c %.S
vpath %.c $(sort $(dir $(SRC_C)))
vpath %.S $(sort $(dir $(SRC_S)))

ELF=$(BUILD_DIR)/$(TARGET).elf
BIN=$(BUILD_DIR)/$(TARGET).bin
DIS=$(BUILD_DIR)/$(TARGET).dis
UF2=$(BUILD_DIR)/$(TARGET).uf2

.PHONY : all clean d c

all: $(BUILD_DIR) $(BIN) $(DIS) 

$(BUILD_DIR):
	mkdir $@

# cc .c
$(BUILD_DIR)/%.o:%.c 
	@echo .CC $<
	@$(CC) $(CFLAGS) -c $< $(INC) -o $@

# as .S
$(BUILD_DIR)/%.o:%.S 
	@echo .AS $<
	@$(AS) $(CFLAGS) -c $< $(INC) -o $@

# elf
$(ELF):$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo link elf $@
	@$(CC) $(OBJC) $(OBJS) $(LDFLAGS)  -o $@
	@$(SZ) $@ 
#	../../tools/elf2uf2 $(ELF) $(UF2)
	../../tools/picotool uf2 convert  --verbose  $(ELF)  $(UF2) 

#cp .bin
$(BIN):$(ELF)
	@echo objcopy bin
	$(CP) -O binary -S $< $@


$(DIS):$(ELF)
	@echo objdump dis
	@$(DP) -D -h -s $< > $@

clean:
	rm -rf $(BUILD_DIR)

d:
	make clean
	make all -j12

c:$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo .o

#  openocd 下载 -s 指定默认目录 -f 都在此目录下工作可以省略前缀
#  program 编程
download1: 
	../../tools/xpack-openocd-0.12.0-6/bin/openocd.exe \
	-s ../../tools/xpack-openocd-0.12.0-6/openocd/scripts \
	-f interface/cmsis-dap.cfg \
	-f target/rp2040.cfg \
	-c "program build/nano.elf reset" \
	-c "reset run" \
	-c exit

download:
#  openocd 下载 -s 指定默认目录 -f 都在此目录下工作可以省略前缀
#  program 编程 
	../../tools/openocd-rpxx/openocd.exe \
	-s ../../tools/openocd-rpxx/scripts \
	-f interface/cmsis-dap.cfg \
	-f target/rp2040.cfg \
	-c "program build/nano.elf reset" \
	-c "reset run" \
	-c exit